package com.funtonow.jqdk.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.LoanListAdapter;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.base.UrlUtils;
import com.funtonow.jqdk.bean.GameThirdInfoListBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.utils.AppUtils;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.PhoneUtils;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.ToastUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import okhttp3.Call;

import static com.funtonow.jqdk.base.UrlUtils.TUI_JIAN;

/**
 * @author Jiajien
 * @date 2019/6/25
 * 审核结果
 */
public class ExamineFailActivity extends BaseActivity {

    @BindView(R.id.tv_countdown)
    TextView tvCountDown;
    @BindView(R.id.rlv_recommend)
    RecyclerView rlvRecommend;
    @BindView(R.id.ll_recommend)
    LinearLayout llRecommend;
    @BindView(R.id.tv_audit_result)
    TextView tvAuditResult;
    @BindView(R.id.tv_audit_result1)
    TextView tvAuditResult1;

    private CountDownTimer countDownTimer;
    private LoanListAdapter recommendAdapter;
    private List<GameThirdInfoListBean> gameThirdInfoListBeans = new ArrayList<>();


    @Override
    public int getLayoutRes() {
        return R.layout.activity_examine_fail;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
//        if (AppUtils.getAppName(this).equals(getString(R.string.ssq_app_name))) {
//            initToolbar("审核");
//        } else {
        initToolbar(getResources().getString(R.string.title_user_info));
//        }
        initRecyclerView(rlvRecommend);
        recommendAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (SPUtil.getUserInfo() != null && recommendAdapter.getItem(position).getVipfw() == 1
                        && SPUtil.getUserInfo().getHasVip() == 0) {
                    ToastUtils.show("该产品仅限会员申请");
                    startActivity(new Intent(ExamineFailActivity.this, VipActivity.class));
                } else {
                    GameThirdInfoListBean gameThirdInfoListBean = recommendAdapter.getItem(position);
                    assert gameThirdInfoListBean != null;
                    StatisticsUtils.clickUrl(gameThirdInfoListBean);
                    StatisticsUtils.intentWebView(ExamineFailActivity.this,
                            gameThirdInfoListBean.getUrl(), gameThirdInfoListBean.getName(),
                            gameThirdInfoListBean.getChanpinid());
                }
            }
        });
        if (getIntent().getBooleanExtra("isFail", false)) {
            tvAuditResult.setText("抱歉您未通过终审");
            tvCountDown.setVisibility(View.GONE);
            if (AppUtils.getAppName(this).equals(getString(R.string.ssq_app_name))) {
                tvAuditResult1.setText("可30天后提交申请再次评估");
                llRecommend.setVisibility(View.GONE);
            } else {
                tvAuditResult1.setText("可明日提交申请再次评估");
                getAppId();
                llRecommend.setVisibility(View.VISIBLE);
            }
        } else {
            if (AppUtils.getAppName(this).equals(getString(R.string.ssq_app_name))) {
                countDownTime(30);
                llRecommend.setVisibility(View.GONE);
            } else {
                countDownTime(180);
                getAppId();
                llRecommend.setVisibility(View.VISIBLE);
            }
        }
    }

    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recommendAdapter = new LoanListAdapter();
        recyclerView.setAdapter(recommendAdapter);
    }

    /**
     * 推荐列表
     */
    private void recommend() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        param.put("showappid", Constants.DATA_APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(TUI_JIAN, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                JSONObject jsonObject = JSON.parseObject(SqjAppliaction.loanInfoBean.getCpMap());
                String jsonArray = JSON.parseObject(jsonString).getJSONArray("data").toJSONString();
                List<String> stringList = JSON.parseArray(jsonArray, String.class);
                for (String s : stringList) {
                    for (LoanInfoBean.HeziInfoListBean heziInfoListBean : SqjAppliaction.loanInfoBean.getHeziInfoList()) {
                        if (s.equals(heziInfoListBean.getGdid())) {
                            for (LoanInfoBean.GdlistBean gdlistBean : SqjAppliaction.loanInfoBean.getGdlist()) {
                                if (s.equals(gdlistBean.getGdid())) {
                                    GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                                    gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                                    gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                                    gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                                    gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                                    gameThirdInfoListBean.setGdId(s);
                                    gameThirdInfoListBeans.add(gameThirdInfoListBean);
                                }
                            }
                        }
                    }
                }
                if (gameThirdInfoListBeans.size() > 0) {
                    recommendAdapter.setNewData(gameThirdInfoListBeans);
                    llRecommend.setVisibility(View.VISIBLE);
                } else {
                    llRecommend.setVisibility(View.GONE);
                }
                StatisticsUtils.baoGuang(Constants.HEZI_ID_25);
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    public void countDownTime(int time) {
        final int finishTime = PhoneUtils.getNum(10, 60);
        /** 倒计时60秒，一次1秒 */
        countDownTimer = new CountDownTimer(time * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                // TODO Auto-generated method stub
                tvCountDown.setText(String.format(Locale.getDefault(), "%ds", millisUntilFinished / 1000));
                if ((int) (millisUntilFinished / 1000) == finishTime) {   // 倒计时跳转界面
                    startActivity(new Intent(ExamineFailActivity.this, ExamineSuccessActivity.class));
                }
            }

            @Override
            public void onFinish() {


            }
        }.start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    /**
     * 获取数据appId
     */
    private void getAppId() {
        HttpUtil.getInstance().getDataAsynFromNet(UrlUtils.GET_APPID, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                Constants.DATA_APP_ID = JSON.parseObject(jsonString).getString("appId");
                recommend();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

}
